﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Pasteles.Controler;
using Pasteles.DataBase;

namespace Pasteles
{
    public partial class CheckTables : Form
    {
        private long id;
        private long receiptNo;
        private XmlDocument doc = new XmlDocument();
        StringProcessing objStringProcessor = new StringProcessing();
        public Printer objPrinter = new Printer("CashierFormLog.txt");
        Connection cnn = new Connection("config.xml");
        public CheckTables()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Lay số id bàn
        /// </summary>
        /// <param name="i">Số id</param>
        public CheckTables(int id)
        {
            InitializeComponent();
            this.id = id;
            lb_TableNo.Text += " " + id.ToString();
            long Total = 0;//luu tong so tien
            doc.Load("OnTable.xml");
            string xPath = "/Tables/table[@id='" + id.ToString() + "']/pastry";
            XmlNodeList nodelist = doc.SelectNodes(xPath);
            foreach (XmlNode node in nodelist)
            {
                string name = node.Attributes["name"].Value;
                int quantity = int.Parse(node.ChildNodes[0].InnerText);
                int price = int.Parse(node.ChildNodes[1].InnerText);
                string idCake = node.Attributes["idcake"].Value;
                int Off = int.Parse(node.ChildNodes[2].InnerText);
                string[] item={name,quantity.ToString(),price.ToString(),Off.ToString(),idCake};
                ListViewItem lvi = new ListViewItem(item);
                lv_checkout.Items.Add(lvi);
                Total += quantity * price;
            }
            
            txt_Total.Text = Total.ToString();//hien thi tong so tien
          
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private long getLatestReceiptID()
        {
            long lReceiptNoLocal = 0;
            string sQuery = "select max(hoa_don.ma_hoa_don) from hoa_don;";
            try
            {

                foreach (DataRow dr in cnn.excecuteQueryToDataTable(sQuery).Rows)
                {
                    lReceiptNoLocal = Convert.ToInt64(dr[0]);
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Push data error: " + ex.ToString());
            }
            //connection.Close();
            return lReceiptNoLocal;
        }

        private void btn_CheckOut_Click(object sender, EventArgs e)
        {
            
            string xpath = "/Tables/table[@id=" + id.ToString() + "]";
            XmlNode node = doc.SelectSingleNode(xpath);
            string sTotalCostToPrint = txt_Total.Text;
            string sCash = txt_Cash.Text;
            string sChange = txt_Change.Text;
            string s_chitiethd = "";
            int maPhongBan = 1;
            int maDonDatHang = 1;
            string maNV = LoginForm.manv;
            string sBillHeader = cnn.preparingBillHeader();
            string s1 = "", s2 = "", s3 = "", s4 = "";
            receiptNo = getLatestReceiptID() + 1;
            if (node.HasChildNodes)
            {
                while (node.ChildNodes.Count >= 1)
                {
                    node.RemoveChild(node.FirstChild);
                }
            }
            doc.Save("OnTable.xml");

           //----------------------------Lap Hoa Don-------------------------
            String sSaveBillQuery = "INSERT INTO hoa_don (MA_HOA_DON, NGAY_LAP_HOA_DON, TONG_GIA_TRI_HOA_DON, CHIET_KHAU) VALUES (" + receiptNo + ", now(), " + sTotalCostToPrint + ", 1);";
            MessageBox.Show("In Hóa Đơn Số: "+receiptNo.ToString());
            try
            {
                cnn.excecuteQuery(sSaveBillQuery);
            }
            catch (Exception er)
            {
                objPrinter.logToFile(er.ToString());
            }
            objPrinter.logToFile(sBillHeader + "\r\n" + sBillHeader.Length.ToString());
            CustomerIDfromMySQLTB.objPrinter.safePrinting(sBillHeader);
            CustomerIDfromMySQLTB.objPrinter.safePrinting("          BAN SO: " + id + "\r\n");
            CustomerIDfromMySQLTB.objPrinter.safePrinting("##############################\r\n");
            foreach (ListViewItem dataItems in lv_checkout.Items)
            {
                string s_lvtenbanh = dataItems.SubItems[0].Text;
                string s_lvsoluong = dataItems.SubItems[1].Text;
                string s_lvdongia = dataItems.SubItems[2].Text;
                string s_lvidbanh = dataItems.SubItems[4].Text;
                long s_thanhtien = long.Parse(s_lvdongia) * long.Parse(s_lvsoluong);
                s_chitiethd = s_chitiethd + objStringProcessor.stringReceipt(s_lvtenbanh, s_lvsoluong, s_lvdongia);
                string sQuery2 = "INSERT INTO  chi_tiet_hoa_don (MA_NHAN_VIEN, MA_PHONG_BAN, MA_BANH, " +
                            "MA_HOA_DON, MA_DON_DAT_HANG, SO_LUONG_BAN, GIA_BAN, THANH_TIEN,SALE_OFF,DA_XOA) VALUES (" +
                            maNV + "," + maPhongBan + "," +s_lvidbanh+"," + receiptNo + "," +
                            maDonDatHang + "," + s_lvsoluong + "," + s_lvdongia + "," + s_thanhtien + ", 1,0);";
                try
                {
                    cnn.excecuteQuery(sQuery2);
                }
                catch (Exception er)
                {
                    objPrinter.logToFile(er.ToString());
                }
                objPrinter.logToFile(s_lvidbanh);
            }
            objPrinter.logToFile(s_chitiethd + " " + s_chitiethd.Length.ToString());
            CustomerIDfromMySQLTB.objPrinter.safePrinting(s_chitiethd);
            string sBillSummary = "------------------------------\r\n" +
                                  "TONG CONG:\r\n" + sTotalCostToPrint + "\r\n" +
                                  "TIEN MAT:\r\n" + sCash + "\r\n" +
                                  "THOI LAI:\r\n" + sChange + "\r\n";
            string sThanks = "------------------------------\r\n" + "       CAM ON QUY KHACH\r\n" + "         HEN GAP LAI !\r\n";
            objPrinter.logToFile(sBillSummary + "\r\n" + sBillSummary.Length.ToString());
            CustomerIDfromMySQLTB.objPrinter.safePrinting(sBillSummary);
            CustomerIDfromMySQLTB.objPrinter.safePrinting(sThanks);
            CustomerIDfromMySQLTB.objPrinter.safePrinting("\r\n\r\n");

            s1 = sBillHeader;
            s2 = s_chitiethd;
            s3 = sBillSummary;
            s4 = sThanks;
             MessageBox.Show("Đã in hóa đơn: "+receiptNo);

             if (MessageBox.Show("Print another receipt?",
                                 "Receipt is printed",
                                 MessageBoxButtons.YesNo) == DialogResult.Yes)
             {
                 string sNewSecondBill = "\r\nSecond bill\r\n";
                 //safePrinting(sNewSecondBill);
                 objPrinter.logToFile(sNewSecondBill.ToString());
                 objPrinter.logToFile(s1 + s1.Length.ToString());
                 CustomerIDfromMySQLTB.objPrinter.safePrinting(s1);
                 CustomerIDfromMySQLTB.objPrinter.safePrinting("          BAN SO: " + id + "\r\n");
                 CustomerIDfromMySQLTB.objPrinter.safePrinting("##############################\r\n");
                 objPrinter.logToFile(s2 + s2.Length.ToString());
                 CustomerIDfromMySQLTB.objPrinter.safePrinting(s2);
                 objPrinter.logToFile(s3 + s3.Length.ToString());
                 CustomerIDfromMySQLTB.objPrinter.safePrinting(s3);
                 objPrinter.logToFile(s4 + s4.Length.ToString());
                 CustomerIDfromMySQLTB.objPrinter.safePrinting(s4);
                 CustomerIDfromMySQLTB.objPrinter.safePrinting("\r\n\r\n");
             }
             this.Close();
        }

        private void txt_Cash_TextChanged(object sender, EventArgs e)
        {
            txt_Change.Text = (int.Parse(txt_Cash.Text) - int.Parse(txt_Total.Text)).ToString();
        }
    }
}
